package com;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

import com.swtdesigner.SWTResourceManager;
import com.topway.dsmflex.Alert;
import com.topway.dsmflex.thread.job.SynchroManager;
import com.topway.dsmflex.thread.job.SynchroMonitor;
import com.topway.dsmflex.ui.InitFormComposite;
import com.topway.dsmflex.ui.Welcome;
import com.topway.dsmflex.ui.composite.servers.ServersMonitor;
import com.topway.dsmflex.ui.composite.synchro.FileSynchro;
import com.topway.dsmflex.ui.composite.synchro.SqlSynchro;
import com.topway.dsmflex.ui.composite.synchro.SystemLog;
import com.topway.dsmflex.ui.composite.synchro.TableSynchro;
import com.topway.dsmflex.ui.dialog.AboutDialog;
import com.topway.dsmflex.ui.dialog.DataSourceDialog;

/**
 * 
 * @author liusy 2013-04-28
 *
 */
public class Application  {
	
	private static Logger log = Logger.getLogger(Application.class);

	protected Shell shell;
	private CTabFolder tabFolder;

	public Map<String, Control> compsoites = new HashMap<String, Control>();
	
	private static final String COMMAND_SHOW_CONSOLE = "数据同步";
	private static final String COMMAND_EXIT = "退出";
	private static final String SYSTEM_NAME = "需求则数据同步系统";
	
	private SynchroMonitor synchroMonitor = null;
	
	public static Application window = null;
	
	
	
   public static void main(String[] args) {
		try {
			AppContext.init();
			window = new Application();
			window.open();
		} catch (Exception e) {
			log.error("Application Error:", e);
			e.printStackTrace();
		}
   }
   
   public static void openMenu(String tabName)
   {
	   window.openTab(tabName);
   }

	public void open() {
		final Display display = Display.getDefault();
		initForm();
		createContents();
		createComps();
		createSystemTray();
		setPos(display);
		Alert.InitAlert(shell);
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}
	public void initForm()
	{
		 this.synchroMonitor = SynchroMonitor.getSynchroMonitor();
		//Display.getDefault().asyncExec(this);
	}

   /**
    * Create contents of the window
    */
   protected void createContents() {
      shell = new Shell();
      shell.setImage(SWTResourceManager.getImage(Application.class, "/img/2010060902463514_easyicon_cn_48.png"));
      shell.setLayout(new FillLayout());
      shell.setSize(930, 550);
      shell.setText(SYSTEM_NAME);
	  shell.addShellListener(new ShellListener() {
	           public void shellDeactivated(org.eclipse.swt.events.ShellEvent e) {
	               //System.out.println("shellDeactivated");
	           }
	           public void shellActivated(org.eclipse.swt.events.ShellEvent e) {
	               //System.out.println("shellActivated");
	           }
	           public void shellClosed(org.eclipse.swt.events.ShellEvent e) {
	        	   shell.setVisible(false);
	           }
	           public void shellDeiconified(org.eclipse.swt.events.ShellEvent e) {
	              // System.out.println("shellDeiconified");
	           }
	           public void shellIconified(org.eclipse.swt.events.ShellEvent e) {
	               // 最小化时不显示在任务栏
	               shell.setVisible(false);
	           }

	       });
	  
	  
	  tabFolder = new CTabFolder(shell, SWT.CLOSE | SWT.FLAT | SWT.BORDER);
      tabFolder.setBorderVisible(true);
      
      tabFolder.addSelectionListener(new SelectionAdapter() {
		@Override
		public void widgetSelected(SelectionEvent arg0) {
			CTabItem ct =(CTabItem) arg0.item;
			InitFormComposite initFormComposite =(InitFormComposite)compsoites.get(ct.getText());
			if(null!=initFormComposite)
			{
				int result = initFormComposite.initForm();
			}
		}
	});

      final CTabItem tabItem = new CTabItem(tabFolder, SWT.NONE);
      tabItem.setText(Welcome.name);
      tabItem.setShowClose(true);
      final Welcome welcome = new Welcome(tabFolder, SWT.NONE);
      tabItem.setControl(welcome);
      
      final Menu menu = new Menu(shell, SWT.BAR);
      shell.setMenuBar(menu);

      //------------------------------系统管理-------------------------------
      final MenuItem mnuSystem = new MenuItem(menu, SWT.CASCADE);
      mnuSystem.setImage(SWTResourceManager.getImage(Application.class, "/img/computer.png"));
      mnuSystem.setText("系统(&S)");

      final Menu menu_1 = new Menu(mnuSystem);
      mnuSystem.setMenu(menu_1);

      final MenuItem mnuConfig = new MenuItem(menu_1, SWT.NONE);
      mnuConfig.setImage(SWTResourceManager.getImage(Application.class, "/img/database_gear.png"));
      mnuConfig.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 DataSourceDialog dsd = new DataSourceDialog(shell);
        	 dsd.open();
         }
      });
      mnuConfig.setText("数据源配置(&C)");
      
      final MenuItem mnuLog = new MenuItem(menu_1, SWT.NONE);
      mnuLog.setImage(SWTResourceManager.getImage(Application.class, "/img/log.png"));
      mnuLog.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 openTab(SystemLog.name);
         }
      });
      mnuLog.setText("系统日志(&L)");
     
      

      final MenuItem mnuExit = new MenuItem(menu_1, SWT.NONE);
      mnuExit.setImage(SWTResourceManager.getImage(Application.class, "/img/door-open-out.png"));
      mnuExit.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
            goExit();
         }
      });
      mnuExit.setText("退出(&E)");

      
      
    //------------------------------数据同步-------------------------------
      final MenuItem mnuLoad = new MenuItem(menu, SWT.CASCADE);
      mnuLoad.setImage(SWTResourceManager.getImage(Application.class, "/img/data.gif"));
      mnuLoad.setText("数据同步(&D)");

      final Menu menu_3 = new Menu(mnuLoad);
      mnuLoad.setMenu(menu_3);
      
      final MenuItem mnuTabSynchro = new MenuItem(menu_3, SWT.NONE);
      mnuTabSynchro.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 openTab(TableSynchro.name);
         }
      });
      mnuTabSynchro.setText("表同步(&T)");
      mnuTabSynchro.setImage(SWTResourceManager.getImage(Application.class, "/img/table.png"));
      
      final MenuItem mnuSqlSynchro = new MenuItem(menu_3, SWT.NONE);
      mnuSqlSynchro.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 openTab(SqlSynchro.name);
         }
      });
      mnuSqlSynchro.setText("SQL同步(&S)");
      mnuSqlSynchro.setImage(SWTResourceManager.getImage(Application.class, "/img/sql.png"));
      

      
      final MenuItem mnuFileSynchro = new MenuItem(menu_3, SWT.NONE);
      mnuFileSynchro.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 openTab(FileSynchro.name);
         }
      });
      mnuFileSynchro.setText("文件同步(&F)");
      mnuFileSynchro.setImage(SWTResourceManager.getImage(Application.class, "/img/file_obj.gif"));
      
    //------------------------------监控管理-------------------------------
      final MenuItem mnuMonitor = new MenuItem(menu, SWT.CASCADE);
      mnuMonitor.setImage(SWTResourceManager.getImage(Application.class, "/img/monitor.png"));
      mnuMonitor.setText("监控管理(&M)");
      
      final Menu menu_servers = new Menu(mnuMonitor);
      mnuMonitor.setMenu(menu_servers);
      
      final MenuItem mnuServers = new MenuItem(menu_servers, SWT.NONE);
      mnuServers.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 openTab(ServersMonitor.name);
         }
      });
      mnuServers.setText("服务器(&S)");
      mnuServers.setImage(SWTResourceManager.getImage(Application.class, "/img/servers.png"));
      
      
    //------------------------------帮助-------------------------------
      final MenuItem mnuHelp = new MenuItem(menu, SWT.CASCADE);
      mnuHelp.setImage(SWTResourceManager.getImage(Application.class, "/img/help.png"));
      mnuHelp.setText("帮助(&H)");

      final Menu menu_2 = new Menu(mnuHelp);
      mnuHelp.setMenu(menu_2);

      final MenuItem mnuAbout = new MenuItem(menu_2, SWT.NONE);
      mnuAbout.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
        	 AboutDialog ad = new AboutDialog(shell);
        	 ad.open();
         }
      });
      mnuAbout.setText("关于(&A)");
      mnuAbout.setImage(SWTResourceManager.getImage(Application.class, "/img/info.gif"));
      
      
      
   }
  
   private void goExit() {
      shell.dispose();
		System.exit(0);
   }

   private void openTab(String name) {
      for (int i = 0; i < tabFolder.getItems().length; i++) {
         CTabItem cti = tabFolder.getItem(i);
         if (cti.getText().equals(name)) {
            tabFolder.setSelection(cti);
            return;
         }
      }
      if (compsoites.get(name) != null) {
         CTabItem cti = new CTabItem(tabFolder, SWT.NONE);
         cti.setText(name);
         cti.setControl(compsoites.get(name));
         tabFolder.setSelection(cti);
      }
   }
   
   
   private void createComps() {
	 TableSynchro tableSynchro =new TableSynchro(tabFolder, SWT.NONE);
	 compsoites.put(TableSynchro.name, tableSynchro);
      SystemLog systemLog =new SystemLog(tabFolder, SWT.NONE);
     compsoites.put(SystemLog.name, systemLog);
     SqlSynchro sqlSynchro =new SqlSynchro(tabFolder, SWT.NONE);
	 compsoites.put(SqlSynchro.name, sqlSynchro);
	 FileSynchro fileSynchro =new FileSynchro(tabFolder, SWT.NONE);
	 compsoites.put(FileSynchro.name, fileSynchro);
	 ServersMonitor serversMonitor = new ServersMonitor(tabFolder, SWT.NONE);
	 compsoites.put(ServersMonitor.name, serversMonitor);
   }

   private void setPos(Display display) {
     // shell.setSize(1024, 768);
      Rectangle rec = Display.getCurrent().getClientArea();
      shell.setLocation(rec.width / 2 - 512, rec.height / 2 - 350);
   }
   
   public void createSystemTray() {
       // 在任务栏不显示
       final int hWnd = shell.handle;
       OS.SetWindowLong(hWnd, OS.GWL_EXSTYLE, OS.WS_EX_CAPTIONOKBTN);

       Display display = shell.getDisplay();
       // Image image = new Image (display, 16, 16);
       final Tray tray = display.getSystemTray();
       final TrayItem trayItem = new TrayItem(tray, SWT.NONE);
       trayItem.setToolTipText(COMMAND_SHOW_CONSOLE);
       trayItem.setImage(SWTResourceManager.getImage(Application.class, "/img/2010060902463514_easyicon_cn_48.png"));
       trayItem.addListener(SWT.Show, new Listener() {
           public void handleEvent(Event event) {
               System.out.println("show");
           }
       });
       trayItem.addListener(SWT.Hide, new Listener() {
           public void handleEvent(Event event) {
               System.out.println("hide");
           }
       });

       // 托盘单击事件
       trayItem.addListener(SWT.Selection, new Listener() {
           public void handleEvent(Event event) {
           }
       });

       // 托盘双击事件
       trayItem.addListener(SWT.DefaultSelection, new Listener() {
           public void handleEvent(Event event) {
           //    System.out.println("default selection");
               shell.setVisible(true);
               shell.setMinimized(false);
               shell.setMaximized(false);
           }
       });

       // 添加托盘右键菜单
       final Menu menu = new Menu(shell, SWT.POP_UP);

       final MenuItem menuStart = new MenuItem(menu, SWT.PUSH);//开始 
       final MenuItem menuStop = new MenuItem(menu, SWT.PUSH);//暂停、恢复
       new MenuItem(menu, SWT.SEPARATOR);// 分割条
       final MenuItem menuExit = new MenuItem(menu, SWT.PUSH);//退出
       
       
       menuStart.setImage(SWTResourceManager.getImage(Application.class, "/img/start.png"));
       menuStart.setText("启动");
       menuStart.addSelectionListener(new SelectionListener() {
           public void widgetSelected(SelectionEvent e) {
        	  // synchroMonitor.start(5);
        	   SynchroManager.getSynchroManager().start();
        	   menuStart.setEnabled(false);
        	   menuStop.setEnabled(true);
           }
           public void widgetDefaultSelected(SelectionEvent e) {
               // widgetSelected(e);
           }
       });

       menuStop.setImage(SWTResourceManager.getImage(Application.class, "/img/suspend.png"));
       menuStop.setText("暂停");
       menuStop.setEnabled(false);
       menuStop.addSelectionListener(new SelectionListener() {
           public void widgetDefaultSelected(SelectionEvent e) {
           }
           public void widgetSelected(SelectionEvent e) {
        	   if(menuStop.getText().equals("暂停"))
        	   {
        		   menuStop.setText("恢复");
        		  //synchroMonitor.suspendSynchro();
        		   SynchroManager.getSynchroManager().suspendSynchro();
        		   menuStop.setImage(SWTResourceManager.getImage(Application.class, "/img/suspend.png"));
        	
        		   menuStop.setEnabled(false);
        		   Thread t =   new Thread() {
        	    	   int i=0;
        	    	   boolean flag = true;
        	           public void run() {
        	        	   while(flag)
        	        	   {
				        	        	  try {
				        	        		  Display.getDefault().asyncExec(new Thread() {
				        	        			  public void run() {
				        	        				  menuStop.setText("恢复("+i+++")");
				        	        			  }
				        	        		  });
											this.sleep(1000);
											if(i>10)
											{
												flag = false;
												  Display.getDefault().asyncExec(new Thread() {
					        	        			  public void run() {
					        	        				  menuStop.setText("恢复");
					        	        				  menuStop.setEnabled(true);
					        	        			  }
					        	        		  });
												this.interrupt();
											}
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
        	        	   }
        	           }
        	        };
        	        t.start();
        	       
        	       
        	   }
        	   else
        	   {
        		   menuStop.setImage(SWTResourceManager.getImage(Application.class, "/img/resume.png"));
          		   menuStop.setText("暂停");
        		 //  synchroMonitor.resumeSynchro();
          		 SynchroManager.getSynchroManager().resumeSynchro();
        	   }
           }
       });
       

       
       
       

       menuExit.setText(COMMAND_EXIT);
       menuExit.addSelectionListener(new SelectionListener() {
           public void widgetSelected(SelectionEvent e) {
        	   goExit();
           }
           public void widgetDefaultSelected(SelectionEvent e) {
           }
       });
       menuExit.setImage(SWTResourceManager.getImage(Application.class, "/img/door-open-out.png"));

       
       trayItem.addListener(SWT.MenuDetect, new Listener() {
           public void handleEvent(Event event) {
               menu.setVisible(true);
               if (shell.isVisible()) {
//                   menu.getItem(0).setEnabled(synchroMonitor.runState());
//                   menu.getItem(1).setEnabled(!synchroMonitor.runState());
               }
           }
       });

   }

   
}
